<?php
/**
 * 用户/消费者相关操作控制器
 * @author hebox
 * @date 2016
 */

namespace Home\Controller;


use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\SendSMS;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CustomerModel;
use Think\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Think\Cache\Driver\Redis;

class CustomerController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 取消费者的基本信息
     */
    public function getInformation()
    {
        try {
            Request::parse();
            $customerId = I('post.customer_id', 0, 'int');
            $information = D('Customer')->has($customerId);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $information;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * [getProvinceData 读取文件省市信息，省市联动]
     * @return [type] [description]
     */
    public function getProvinceData(){
        $json='province.json';
        if(!file_exists($json)){
            $this->ajaxReturn(['code'=>400,'data'=>[],'msg'=>'省份获取失败']);
        }
        
        // echo  file_get_contents($json);
        $p=file_get_contents($json);
        $p=json_decode($p);
        $this->ajaxReturn(['data'=>$p]);
        //echo  '123';
    }

    /**
     * 保存消费者的基本信息
     */
    public function saveInformation()
    {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $cur_customer = D('Customer')->has($customerId);

            $mobile = I('post.mobile', '', 'mobile');

            if($cur_customer['amount'] <= 0 && $cur_customer['isset_pay_pass']){
                //手机号唯一，每个手机号只能申请一次
                $res = M('Customer')->where(['mobile' => $mobile, 'status' => ['neq',Constant::CUSTOMER_DEL],
                    'id'=>['neq', $customerId]])->field('id')->select();
                if($res){
                    BusinessException::throwException(Constant::CUSTOMER_MOBILE_EXIST);
                }
            }

            $verifyCode = I('post.verify_code', 0, 'int');

            if (!$verifyCode) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $sentVerifyCode = SendSMS::getVerifyCode($mobile, Constant::VERIFY_CODE_TYPE_ACTIVE);
            if (!$sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }

            if ($verifyCode != $sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            $customer = M('Customer')->where(['id' => $customerId]);
            $data = [
                'mobile' => $mobile,
                'status' => Constant::CUSTOMER_USE
            ];

            $officeTel = I('post.office_tel', '', 'string');
            if ($officeTel) {
                $data['office_tel'] = $officeTel;
            }

            //保存用户信息时增加工作单位
            $officeName = I('post.office_name', '', 'string');
            if ($officeName) {
                $data['company'] = $officeName;
            }

            // @todo 与商家合影
            if (false) {
                $merchantPhoto = I('post.merchant_photo', '', 'string');
                if (!$merchantPhoto) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }

                $fileName = $customerId . $merchantPhoto;
                if (!file_exists(get_photo_path($fileName, $_type = 'customer'))) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            if (false === $customer->save($data)) {
                BusinessException::throwException(Constant::FAILED);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            SendSMS::rmVerifyCode($mobile, Constant::VERIFY_CODE_TYPE_ACTIVE);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function saveIdCardInformation()
    {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            
            $type = I('post.type', 0, 'int');
            $idNum = I('post.id_num', '', 'string');
            $realName = I('post.real_name', '', 'string');
            Log::face_write("*****************用户".$customerId."接到的身份证信息：".$idNum."认证方式".$type);
            if(!$customerId || !$type){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $cur_cutomer = D('Customer')->has($customerId);

            //获取用户认证信息
            $auth = D('CustomerAuth')->getCustomerAuth($customerId);
            
//            //身份证号已经存在，不能继续绑定
//             if($auth['id_num']){
//                 BusinessException::throwException(Constant::ID_NUM_AUTHED);
//             }
            //校验身份证是否被其他用户注册过
             if(!$cur_cutomer['id_num']){
                 $id = M('Customer')->where(['id_num'=>$idNum])->field('id')->find();
                 if($id){
                     BusinessException::throwException("你的身份证已经注册过，不能再次注册");
                 }
             }

            //扫身份证方式
            if(Constant::REPAY_TYPE_SCAN == $type){
                    //当前用户如果已经记录过身份证了，则校验该用户的身份证两次是否一致
                    if($cur_cutomer['id_num'] && ($cur_cutomer['id_num'] != $idNum)){
                        BusinessException::throwException(Constant::ID_NUM_DIFF);
                    }
                    $data = [
                            'id' => $customerId,
                            'real_name' => I('post.real_name', '', 'string'),
                            'id_num' => I('post.id_num', '', 'string'),
                            'gender' => I('post.gender', '', 'string'),
                            'nation' => I('post.nation', '', 'string'),
                            'birthday' => I('post.birthday', '', 'string'),
                            'birthplace' => I('post.birthplace', '', 'string'),
                            'sign_organ' => I('post.sign_organ', '', 'string'),
                            'valid_period' => I('post.valid_period', '', 'string'),
                            'mobile' => $cur_cutomer['mobile']
                        ];
                    Log::face_write("*****************用户".$customerId."从face++数据|身份证:".I('post.id_num', '', 'string').",真实姓名:".I('post.real_name', '', 'string').",身份证住址:".I('post.birthplace', '', 'string').",总的数据".json_encode($data));
                        foreach ($data as $idInformation) {
                            if (!$idInformation) {
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                        }

            }

            //输入身份证id方式
            // if(Constant::REPAY_TYPE_IDNUM == $type){
            //     $idNum = I('post.id_num', 0, 'string');
            //     $realName = I('post.real_name', '', 'string');
            // if(!$realName || !$idNum){
            //     BusinessException::throwException(Constant::INVALID_PARAMETER);
            // }else{
            //     $res = D("Customer")->getAddressById($idNum);
            //     if($res){
            //         $data = [
            //             'id' => $customerId,
            //             'real_name' => $realName,
            //             'id_num' => $idNum,
            //             'gender' => $res['sex'],
            //             'birthday' => $res['birthday'],
            //             'birthplace' => $res['area'],
            //             'mobile' => $cur_cutomer['mobile']
            //         ];
            //     }else{
            //         BusinessException::throwException(Constant::MERCHANT_CREDIT_ERROR);
            //     }
            // }

            // }

            //录入身份证信息
            $Customer = M('Customer');
            if (false === $Customer->save($data)) {
                Log::face_write("*****************用户".$customerId."修改入库结果".$Customer->save($data));
                BusinessException::throwException(Constant::CUSTOMER_SAVE_FAILED);
            }

            //录入用户认证信息
            $data_auth['customer_id'] = $customerId;
            $data_auth['id_num'] = 1;
            $auth = M('CustomerAuth')->where(['customer_id'=>$customerId])->find();
            if($auth){
                $data_auth['id'] = $auth['id'];
                $ins = M('CustomerAuth')->save($data_auth);
            }else{
                $ins = D('CustomerAuth')->insCustomerAuth($data_auth);
            }

            //用户资格预筛选(现开启百融+威震认证) 
//			$hook = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data, Constant::DECISION_ENGINE_HOOK);
//            Log::borrow_write("*****************用户".$customerId."黑名单认证|百融认证结果：".json_encode($hook)."*****：");
//            if (Constant::SUCCESS != $hook['code']) {
//				$res_data['qualified'] = 0; //用户不合格，不可以下单
//				$res_data['reason'] = $hook['msg'];
//			}else{
//				$res_data['qualified'] = 1;
//			}
			/*身份证验证-威震*/
            $weizhen = A('Home/Blacklist');
            $data_sql = [];
            $data_sql['idCard'] =$idNum;
            $weizhen_data = $weizhen->ckweizhen($realName,$idNum,$cur_cutomer['mobile']);
            Log::borrow_write("*****************用户".$customerId."黑名单认证|威震认证结果：".json_encode($weizhen_data)."*****：");
            Log::borrow_write("*****************用户".$customerId."黑名单认证|威震认证结果：是否在黑名单：".$weizhen_data['black_result']."|黑名单等级：".$weizhen_data['risk_level']."|*****：");
            if($weizhen_data['black_result']=='Y'&&$weizhen_data['risk_level']=='高'){
                Log::borrow_write("*****************用户".$customerId."进入威震黑名单认证|*****：");

                $res_data['qualified'] = 0; //用户不合格，不可以下单
                $res_data['reason'] = Constant::IN_BLACK_LIST_9F;
                $weizhen->addDataBase($data_sql);
            } else {
                $res_data['qualified'] = 1;
            }
            Log::borrow_write("*****************用户".$customerId."黑名单认证|威震认证未命中*****：");
          /*威震认证结束|开启百融合认证*/
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res_data;
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getPerMonthRepayAmount()
    {
        try {
            $amount = I('post.amount', 0, 'intval');
            if ($amount <= 0) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //计算分期本金和利息,单位分
            $installmentDetail = $this->getInstallmentDetail($amount);
            $principal = $installmentDetail['principal'];
            $interest = $installmentDetail['interest'];

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'amount' => $amount,
                'repay_type' => Constant::PAY_TYPE_INSTALLMENT,
                'repay_date' => date('Y-m-' . Constant::BILL_LAST_DAY, strtotime("+1month")),
                'repay_times' => Constant::REPAY_TIMES,
                'repay_principal' => $principal,
                'repay_interest' => $interest,
                'repay_total' => $principal + $interest,
            ];
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*********************************************************************
     * 功能描述：下发验证码
     * 入参：
     *      "mobile": "用户手机号",
     *      "type": "1:绑定银行卡,2:激活额度(确认身份),3:修改密码"
     * 出参：
     *      "code": 0,
     *      "msg": "success"
     ********************************************************************/
    public function getVerifyCode()
    {
        try {
            $mobile = I('post.mobile', null, 'mobile');
            $type = (int)I('post.type', null, 'int');
            Log::sms_write('customer/getVerifyCode app用户开始短信验证 手机：'.$mobile.' type:'.$type.'  ');
            $validType = [
                Constant::VERIFY_CODE_TYPE_BIND       => '1:绑定银行卡验证码',
                Constant::VERIFY_CODE_TYPE_ACTIVE     => '2:激活额度验证码',
                Constant::VERIFY_CODE_TYPE_MODIFY     => '3:修改支付密码验证码',
                Constant::VERIFY_CODE_TYPE_SIGNUP     => '4:注册用户验证码',
                Constant::VERIFY_CODE_TYPE_LOGIN      => '5:修改登录密码验证码',
                Constant::VERIFY_CODE_MERCHANT_MODPWD => '100:商户端重置密码',
                Constant::VERIFY_CODE_MERCHANT_SIGNUP => '101:商户注册时获取验证码',
            ];
            if (!isset($validType[$type])) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if (!$mobile) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if(Constant::BINDCARDSOURCE=='2'&&$type==Constant::VERIFY_CODE_TYPE_BIND ){//绑卡渠道--易宝--易宝发送验证码
                $cardNum = I('post.card_num', null);
                $customerId = I('post.customer_id', null);
                Log::info_log('app用户绑卡'.$cardNum.' '.$customerId.' 交易中心下发验证码开始');
                if (!$cardNum) {
                    Log::info_log('app用户'.$customerId.'绑卡 下发验证码 异常 卡号不存在');
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                if (!$customerId) {
                    Log::info_log('app用户'.$customerId.'绑卡 下发验证码 异常 客户id不存在');
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                $pay = A('Home/Pay')->bindCardSendSms($customerId,$cardNum,$mobile);
                if($pay){
                    Log::info_log('app用户'.$customerId.'绑卡 下发验证码 成功  ');
                    $ret = Constant::getReturn(Constant::SUCCESS);
                }else{
                    Log::info_log('app用户'.$customerId.'绑卡 下发验证码 失败 ');
                    $ret = Constant::getReturn(Constant::SMSFAILED);
                }
            }else{//走老的下发验证码通道
                if (!SendSMS::verifyCode($mobile, $type)) {
                    Log::sms_write(' customer/getVerifyCode|app用户短信验证失败 ');
                    BusinessException::throwException(Constant::SEND_VERIFY_CODE_FAILED);
                }
                Log::sms_write(' customer/getVerifyCode|app用户短信验证成功 ');
                $ret = Constant::getReturn(Constant::SUCCESS);
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $this->ajaxReturn($ret);
    }
    /**
     * [jumpToReviewedPass 给战达的接口]
     * @return [type] [description]
     */
    public function jumpToReviewedPass(){
        $mobile = I("request.mobile");
        $verifyCode = "123456";

        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
            $content = "【找钱花】尊敬的找钱花用户，您在找钱花申请的额度已经通过审核了，快去看看吧";
            Log::write($mobile." 生成的验证码是：$verifyCode ", Log::DEBUG);
            $ret = SendSMS::yunfeng_send_json($mobile,$content);
            Log::write($mobile." $ret ret=:".json_encode($ret), Log::DEBUG);
            
        /*云峰结束*/
        $res=[];
        if ($ret) {
            $res[]=$ret;
            $res['status']=200;
        } else {
            $res[]=$ret;
            $res['status']=201;
        }
        
        $this->ajaxReturn($res);
    }
/*
* 定时短信---09:30
* 当日与后三天所有到期未还款的客户
*/
    public function crontabCode()
    {
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            die;
        }
            Log::cron_write(' customer/crontabCode|定时短信通知|09:30');
            $redis = new Redis();
        $time=strtotime(date('Y-m-d',time()))-1;
        $time_=$time+4*24*60*60;
        $reslut=D('')->query("
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
");
        $sql_09="
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
";
        Log::cron_write("++++++++++09:30发送失败的手机号码sql查询:".$sql_09.'|结果：'.json_encode($reslut)."+++++++++++++");
        foreach($reslut as $k=>$v){
            $phonenumber = $v['mobile'];
            $name = $v['real_name'];
            $amount = $v['consume_amount']*0.01;
            $date = date('Y-m-d',$v['repayment_time']);
            //$content='【找钱花】尊敬的用户'.$name.'，您本期还款日为'.$date.'，还款金额为'.$amount.'元，请在还款日12:00前保证还款账户有足够资金或自助还款至我司还款账户，如果已还款请自行忽略该短信';
            $content='【找钱花】尊敬的用户'.$name.'，您本期还款日为'.$date.'，还款金额为'.$amount.'元，请在还款日前保证还款账户有足够资金或自助还款至我司还款账户，请及时还款，避免逾期产生罚息，如果已还款请自行忽略该短信';
            Log::cron_write("*********09:30手机号:".$phonenumber."|短信内容:".$content."|*********");
            $key = '控制用户9:30发送提醒短信次数'.$phonenumber;
            $num = $redis->get($key);
            if (empty($num)){
                $redis->set($key,$phonenumber,72000);
                $ret = SendSMS::yunfeng_send_json($phonenumber,$content);
                Log::cron_write("*********09:30发送短信结果:".$ret."redis：key".$key);
            } else {
                Log::cron_write("*********09:30发送短信失败原因多次发送,发送时间:".date("Y-m-d h:i:s",time())."redis：key".$key);
                continue;
            }
            usleep(2);
        }
    }

    /*
* 定时短信---13:30|17:00
* 当日到期未还款客户
*/
    public function crontabCode_one()
    {
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            die;
        }
        Log::cron_write(' customer/crontabCode|定时短信通知|13:00|17:00 ');
        $redis = new Redis();
        $time=strtotime(date('Y-m-d',time()))-1;
        $time_=$time+24*60*60;
        $reslut=D('')->query("
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
");
        $sql_09="
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
";
        Log::cron_write("++++++++++13:30|17:00发送失败的手机号码sql查询:".$sql_09.'|结果：'.json_encode($reslut)."+++++++++++++");
        foreach($reslut as $k=>$v){
            $phonenumber = $v['mobile'];
            $name = $v['real_name'];
            $amount = $v['consume_amount']*0.01;
            $date = date('Y-m-d',$v['repayment_time']);
            //$content = "【找钱花】".$name.",找钱花提示你，今天为还款日，应还金额为".$amount."元，务必在今天下午19:00前保证还款账户有足够资金或通过APP主动还款，避免逾期产生高额违约金及后续其他恶劣影响【找钱花】";
            $content = "【找钱花】".$name.",找钱花提示你，今天为还款日，应还金额为".$amount."元，务必在保证还款账户有足够资金或通过APP主动还款，请及时还款，避免逾期产生罚息";
            Log::cron_write("********13:30|17:00手机号:".$phonenumber."|短信内容:".$content."|*********");
            $key = '控制用户13:30|17:00发送提醒短信次数'.$phonenumber;
            $num = $redis->get($key);
            if (empty($num)){
                $redis->set($key,1,72000);
                $ret = SendSMS::yunfeng_send_json($phonenumber,$content);
                Log::cron_write("*********13:30|17:00发送短信结果:".$ret."redis：key".$key);
            } else {
                if ($num >= 2){
                    Log::cron_write("*********13:30|17:00发送短信失败原因多次发送,发送时间:".date("Y-m-d h:i:s",time())."redis：key".$key);
                    continue;
                } else {
                    $redis->set($key,$redis->get($key)+1,72000);
                    $ret = SendSMS::yunfeng_send_json($phonenumber,$content);
                    Log::cron_write("*********13:30|17:00发送短信结果:".$ret."redis：key".$key);
                }
            }
            usleep(2);
        }
    }
    /*
   * 定时短信---19:00
   * 明日到期还款客户
   */
    public function crontabCode_two()
    {
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            die;
        }
        Log::cron_write(' customer/crontabCode|定时短信通知|19:00  ');
        $redis = new Redis();
        $time=strtotime(date('Y-m-d 23:59',time()))-1;
        $time_=$time+24*60*60;
        $reslut=D('')->query("
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
");
        $sql_09="
select a.id,a.type,a.`status`,a.amount,a.repayment_time,
a.add_time,
a.consume_amount,a.repay_id
,b.mobile,b.real_name
FROM `consume_history`  as a
LEFT JOIN `customer`as b
on a.customer_id=b.id
WHERE a.`type`=5
AND a.`status`=1
AND a.`repayment_time`>".$time."
AND a.`repayment_time`<".$time_."
";
        Log::cron_write("++++++++++13:30|17:00发送失败的手机号码sql查询:".$sql_09.'|结果：'.json_encode($reslut)."+++++++++++++");
        foreach($reslut as $k=>$v){
            $phonenumber = $v['mobile'];
            $name = $v['real_name'];
            $amount = $v['consume_amount']*0.01;
            $date = date('Y-m-d',$v['repayment_time']);
            //$content = "【找钱花】尊敬的找钱花客户".$name.",您本期还款日为".$date."，还款金额为".$amount."元，请在还款日12:00前保证还款账户有足够资金或自助还款至我司还款账户，避免因未及时还款产生不良信用记录及损失【找钱花】";
            $content='【找钱花】尊敬的用户'.$name.'，您本期还款日为'.$date.'，还款金额为'.$amount.'元，请在还款日前保证还款账户有足够资金或自助还款至我司还款账户，请及时还款，避免逾期产生罚息，如果已还款请自行忽略该短信';
            Log::cron_write("*******-19:00手机号:".$phonenumber."|短信内容:".$content."|*********");
            $key = '控制用户19:00发送提醒短信次数'.$phonenumber;
            $num = $redis->get($key);
            if (empty($num)){
                $redis->set($key,$phonenumber,72000);
                $ret = SendSMS::yunfeng_send_json($phonenumber,$content);
                Log::cron_write("*********09:30发送短信结果:".$ret."redis：key".$key);
            } else {
                Log::cron_write("*********09:30发送短信失败原因多次发送,发送时间:".date("Y-m-d h:i:s",time())."redis：key".$key);
                continue;
            }
            usleep(2);
        }
    }
    public function setPayPass()
    {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $payPass = I('post.pay_pass', 0, 'string');
            if (!$payPass) {
                Log::write("*******|setPayPass|customer_id|".$customerId."设置交易密码|密码格式错误".$payPass.'|原值：'.I('post.pass'));
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $data = [
                'id' => $customerId,
                'pay_pass' => get_enc_password($payPass),
            ];

            if (false === M('Customer')->save($data)) {
                Log::write("*******|setPayPass|customer_id|".$customerId."设置交易密码|保存失败|数据:".json_encode($data));
                BusinessException::throwException(Constant::CUSTOMER_SAVE_FAILED);
            }
            Log::write("*******|setPayPass|customer_id|".$customerId."设置交易密码|保存成功".json_encode($data));

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($data);
        $this->ajaxReturn($ret);
    }

    public function verifyPayPass()
    {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $payPass = I('post.pay_pass', 0, 'string');
            $this->_verifyPayPass($customerId, $payPass);

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 检查支付密码
     * @param $customerId
     * @param $payPass
     * @throws BusinessException
     * @throws \Think\Exception
     */
    private function _verifyPayPass($customerId, $payPass)
    {

        D('Customer')->has($customerId);

        $encPayPass = M('Customer')->where(['id' => $customerId])->getField('pay_pass');
        if (!$encPayPass) {
            BusinessException::throwException(Constant::UNSET_PAY_PASS);
        }

        if (password_unmatched($payPass, $encPayPass)) {
            BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
        }
    }


    /**
     * 分期还款下单
     * 这里只对正常消费的记录作处理，如果用户逾期则需要通过定时任务脚本处理
     * @TODO:(mr2longly) 将与orderNextMonth重复的代码提取到一个公共的私有函数中
     * -------------------------------------------------------------------------------
     * 消费总金额      处理方式       授权审批     首次授权金额        非首次处理
     * -------------------------------------------------------------------------------
     *   <100       手机号+验证码     无需审批          100          授信金额不变
     * 100~500      +身份认证信息     无需审批          500          授信金额不变
     * 500~2000     +提高额度信息     需要审批   最少本次消费金额    本次消费金额
     * >2000        +更多信用信息     需要审批   最少本次消费金额    本次消费金额
     * -------------------------------------------------------------------------------
     */
    public function orderInstallmentRepay()
    {
        try {
            // 消费金额
            $amount = $consumeAmount = I('post.amount', 0, 'intval');
            if (!$amount) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            // 验证用户信息
            $customerId = I('post.customer_id', 0, 'intval');
            $customer = D('Customer')->has($customerId);

            // 验证商户信息
            $merchantId = I('post.merchant_id', 0, 'intval');
            $merchant = D('Merchant')->has($merchantId);

            // 验证支付密码
            $payPass = I('post.pay_pass', 0, 'strval');
            $this->_verifyPayPass($customerId, $payPass);

            // 处理优惠信息
            $discountFirstOrder = 0;
            // 首单优惠
            if (0 == $customer['order_count'] && $merchant['discount_first_order'] > 0) {
                $amount -= $merchant['discount_first_order'];
                $discountFirstOrder = $merchant['discount_first_order'];
            }

            // 商户满减
            $discountFullAmount = $discountFullReduce = 0;
            if ($merchant['discount_full_amount'] && $merchant['discount_full_reduce']) {
                // 原始的消费金额与满减金额比较
                if ($consumeAmount >= $merchant['discount_full_amount']) {
                    $amount -= $merchant['discount_full_reduce'];
                    $discountFullReduce = $merchant['discount_full_reduce'];
                }
            }

            // 商户折扣
            $discountRebate = 0;
            if ($merchant['discount_rebate']) {
                // 计算商户折扣金额(扣减商家金额按四舍五入的方式)
                $discountRebate = round(($consumeAmount * (100-$merchant['discount_rebate']*10))/100.0);
                $amount -= $discountRebate;
            }

            // 什么情况下系统都不会倒贴钱
            if ($amount < 0) {
                $amount = 0;
            }

            // 商户应得的金额= $consumeAmount(用户消费原金额) - $discountFullReduce(商户满减优惠)-$discountRebate（商家折扣优惠）
            $merchantGainAmount = $consumeAmount - $discountFullReduce - $discountRebate;

            //地理位置
            $country = I("post.country", '');
            $location = I("post.location", '');
            if (empty($country) || empty($location)) {
                BusinessException::throwException(Constant::INVALID_LOCATION);
            }
            //保存位置信息
            $this->saveLocationHistory();

            //计算分期本金和利息,单位分
            $installmentDetail = $this->getInstallmentDetail($amount);
            $principal = $installmentDetail['principal'];
            $interest = $installmentDetail['interest'];
            //分期后当月账单待还金额
            $currentRepayment = $principal + $interest;

            //设置审核状态 默认未审核
            $data = D("Customer")->where(['id' => $customerId])->find();
            $status = ConsumeHistoryModel::STATUS_UN_REVIEWED;
            if ($amount < Constant::MAX_AMOUNT_NO_NEED_CHECK) {
                $status = ConsumeHistoryModel::STATUS_REVIEWED;
                //如果小于MAX_AMOUNT 且 审核通过则直接把用户的首次500元授信保存
                if (!$data['amount']) {
                    D("Customer")->where(['id' => $customerId])->
                    setField(['amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK, 'balance_amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK]);
                    $data['balance_amount'] = $data['amount'] = Constant::MAX_AMOUNT_NO_NEED_CHECK;
                } else {
                    //如果用户已经授信过了，则需要判断用户的余额是否小于当前的消费金额，如果小则需要待审核
                    if ($data['balance_amount'] < $amount) {
                        $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                    }
                }
            } else {
                //如果大于500则需要判断本次消费是新用户还是老用户，如果是老用户则还需要判断余额是否大于消费金额
                if ($amount <= $data['balance_amount']) {
                    $status = ConsumeHistoryModel::STATUS_REVIEWED;
                } else {
                    $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                }
            }

            //如果提高额度，需要录入qq数据
//            if($status == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
                $qq = I('post.qq', 0, 'string');
//                if(!$qq){
//                    BusinessException::throwException(Constant::INVALID_PARAMETER);
//                }
                if($customer['qq']){
                    if($customer['qq'] != $qq){
                        $customer['qq'] = $data['qq'].'|'.$qq;
                    }
                }else{
                    $customer['qq'] = $qq;
                }
                $res = D("Customer")->where(['id' => $customerId])->setField(['qq' => $customer['qq']]);
//            }
          
            //生成分期还款消费记录
            $consumeData = [
                'amount' => $amount,
                'consume_amount' => $amount,
                'discount_first_order' => $discountFirstOrder,
                'discount_full_amount' => $discountFullAmount,
                'discount_full_reduce' => $discountFullReduce,
                'discount_rebate_amount' => $discountRebate,
                'type' => Constant::PAY_TYPE_INSTALLMENT,
                'customer_id' => $customerId,
                'merchant_id' => $merchantId,
                'status' => $status,
                'repayment_time' => strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', strtotime("+1month"))),
                'add_time' => time(),
                
            ];
            //分期大单入库
            if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
                BusinessException::throwException(Constant::FAILED);
            }
            //D('Customer')->where(['id' => $customerId])->setInc('order_count');
            M('Customer')->execute("UPDATE `customer` SET `order_count`=`order_count` + 1  WHERE  `id` = '$customerId'");
                       
            /* modify at 2016-08-03 for 调整入库顺序，校验不通过的数据需要进行留痕处理 */
            //执行决策引擎
            $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data);
            Log::write("decision exception:" . json_encode($ret));
            if (Constant::SUCCESS != $ret['code']) {
                D('ConsumeHistory')->where(['id' => $insertId])->setField('status', 6);
                BusinessException::throwException($ret['code'], $ret['msg']);
            }
            //生成分期明细
            $installmentData = [];
            // $i 一定要从1开始(原因:分期付款下月才开始还)
            for ($i = 1; $i <= Constant::REPAY_TIMES; $i++) {
                $installmentData[] = [
                    'amount' => $currentRepayment,
                    'parent_id'=>$insertId,
                    'repayment_time' => get_repayment_time($i),
                    'add_time' => time()
                ];
            }
            //分期小单入库
            if (!($installmentId = D('ConsumeInstallmentHistory')->addAll($installmentData))) {
                BusinessException::throwException(Constant::FAILED);
            }

            //没有审核通过直接跳出
            if (ConsumeHistoryModel::STATUS_UN_REVIEWED == $status) {
                BusinessException::throwException(Constant::WAIT_FOR_REVIEW);
            }

            //如果审核通过，写账单，增加商户提现金额，扣减用户授信余额
            if (ConsumeHistoryModel::STATUS_REVIEWED == $status) {
                $billModel = D("CustomerBill");
                if ($billModel->hasRecord($customerId, Constant::PAY_TYPE_INSTALLMENT)) {
                    $billRet = $billModel->updateRepaymentAmount($customerId, $currentRepayment, Constant::PAY_TYPE_INSTALLMENT);
                    if ($billRet) {
                        D("MerchantUser")->updateBalance($merchantId, $merchantGainAmount);
                        //D("Customer")->updateBalance($customerId, -($amount + $interest*Constant::REPAY_TIMES));
                        D("Customer")->updateBalance($customerId, -($amount));
                    }
                } else {
                    $customerBill = [
                        'customer_id' => $customerId,
                        'type' => Constant::PAY_TYPE_INSTALLMENT,
                        'repayment_amount' => $currentRepayment,
                        'bill_date' => $billModel->billDate(),
                        'add_time' => time()
                    ];
                    $billId = $billModel->add($customerBill);
                    if ($billId) {
                        D("MerchantUser")->updateBalance($merchantId, $merchantGainAmount);
                        //D("Customer")->updateBalance($customerId, -($amount + $interest*Constant::REPAY_TIMES));
                        D("Customer")->updateBalance($customerId, -($amount));
                    }
                }
            }

            //数据返回
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'amount' => $consumeAmount,
                'repay_type' => Constant::PAY_TYPE_INSTALLMENT,
                'repay_date' => Constant::BILL_LAST_DAY,
                'repay_times' => Constant::REPAY_TIMES,
                'repay_principal' => $principal,
                'repay_interest' => $interest,
                'repay_total' => $principal + $interest,
            ];

        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        //生成客户端需要的数据
        $this->generateClientData($data, $status, $ret);

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 次月还款
     * @throws \Think\Exception
     */
    public function orderNextMonthRepay()
    {
        try {
            // 消费金额
            $amount = $consumeAmount = I('post.amount', 0, 'intval');
            if (!$amount) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            // 验证用户信息
            $customerId = I('post.customer_id', 0, 'intval');
            $customer = D('Customer')->has($customerId);

            // 验证商户信息
            $merchantId = I('post.merchant_id', 0, 'intval');
            $merchant = D('Merchant')->has($merchantId);

            // 验证支付密码
            $payPass = I('post.pay_pass', 0, 'strval');
            $this->_verifyPayPass($customerId, $payPass);

            // 处理优惠信息
            $discountFirstOrder = 0;
            // 首单优惠
            if (0 == $customer['order_count'] && $merchant['discount_first_order'] > 0) {
                $amount -= $merchant['discount_first_order'];
                $discountFirstOrder = $merchant['discount_first_order'];
            }

            // 商户满减
            $discountFullAmount = $discountFullReduce = 0;
            if ($merchant['discount_full_amount'] && $merchant['discount_full_reduce']) {
                // 原始的消费金额与满减金额比较
                if ($consumeAmount >= $merchant['discount_full_amount']) {
                    $amount -= $merchant['discount_full_reduce'];
                    $discountFullReduce = $merchant['discount_full_reduce'];
                }
            }

            // 商户折扣
            $discountRebate = 0;
            if ($merchant['discount_rebate']) {
                // 计算商户折扣金额(扣减商家金额按四舍五入的方式)
                $discountRebate = round(($consumeAmount * (100-$merchant['discount_rebate']*10))/100.0);
                $amount -= $discountRebate;
            }

            // 什么情况下系统都不会倒贴钱
            if ($amount < 0) {
                $amount = 0;
            }

            // 商户应得的金额= $consumeAmount(用户消费原金额) - $discountFullReduce(商户满减优惠) - $discountRebate（商家折扣优惠）
            $merchantGainAmount = $consumeAmount - $discountFullReduce - $discountRebate;

            //地理位置
            $country = I("post.country", '');
            $location = I("post.location", '');
            if (empty($country) || empty($location)) {
                BusinessException::throwException(Constant::INVALID_LOCATION);
            }

            //保存位置信息
            $this->saveLocationHistory();
            //设置审核状态 默认未审核
            $data = D("Customer")->where(['id' => $customerId])->find();
            $status = ConsumeHistoryModel::STATUS_UN_REVIEWED;
            if ($amount < Constant::MAX_AMOUNT_NO_NEED_CHECK) {
                $status = ConsumeHistoryModel::STATUS_REVIEWED;
                //如果小于MAX_AMOUNT 且 审核通过则直接把用户的首次500元授信保存
                if (!$data['amount']) {
                    D("Customer")->where(['id' => $customerId])->
                    setField(['amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK, 'balance_amount' => Constant::MAX_AMOUNT_NO_NEED_CHECK]);
                    $data['balance_amount'] = $data['amount'] = Constant::MAX_AMOUNT_NO_NEED_CHECK;
                } else {
                    //如果用户已经授信过了，则需要判断用户的余额是否小于当前的消费金额，如果小则需要待审核
                    if ($data['balance_amount'] < $amount) {
                        $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                    }
                }
            } else {
                //如果大于500则需要判断本次消费是新用户还是老用户，如果是老用户则还需要判断余额是否大于消费金额
                if ($amount <= $data['balance_amount']) {
                    $status = ConsumeHistoryModel::STATUS_REVIEWED;
                } else {
                    $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                }
            }
            //如果提高额度，需要录入qq数据
//            if($status == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
                $qq = I('post.qq', 0, 'string');
                /*if(!$qq){
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }*/
                if($customer['qq']){
                    if($customer['qq'] != $qq){
                        $customer['qq'] = $data['qq'].'|'.$qq;
                    }
                }else{
                    $customer['qq'] = $qq;
                }
                $res = D("Customer")->where(['id' => $customerId])->setField(['qq' => $customer['qq']]);
//            }
            //生成次月还款消费记录
            $consumeData = [
                'amount' => $amount,
                'consume_amount' => $consumeAmount,
                'discount_first_order' => $discountFirstOrder,
                'discount_full_amount' => $discountFullAmount,
                'discount_full_reduce' => $discountFullReduce,
                'discount_rebate_amount' => $discountRebate,
                'type' => Constant::PAY_TYPE_NEXT_MONTH,
                'customer_id' => $customerId,
                'merchant_id' => $merchantId,
                'status' => $status,
                'repayment_time' => strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', strtotime("+1month"))),
                'add_time' => time()
            ];
            if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
                BusinessException::throwException(Constant::FAILED);
            }
            /* modify at 2016-08-03 for 调整入库顺序，校验不通过的数据需要进行留痕处理 */
            //执行决策引擎，没有抛异常则通过决策引擎
            $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data);
            Log::write("decision exception:" . json_encode($ret));
            if (Constant::SUCCESS != $ret['code']) {
                D('ConsumeHistory')->where(['id' => $insertId])->setField('status', 6);
                BusinessException::throwException($ret['code'], $ret['msg']);
            }
            //D('Customer')->where(['id' => $customerId])->setInc('order_count');
            M('Customer')->execute("UPDATE `customer` SET `order_count`=`order_count` + 1  WHERE  `id` = '$customerId'");

            //没有审核通过直接跳出
            if (ConsumeHistoryModel::STATUS_WAIT_REVIEWED == $status) {
                BusinessException::throwException(Constant::WAIT_FOR_REVIEW);
            }
            //如果审核通过，写账单，增加商户提现金额，扣减用户授信余额
            if (ConsumeHistoryModel::STATUS_REVIEWED == $status) {
                $billModel = D("CustomerBill");
                if ($billModel->hasRecord($customerId, Constant::PAY_TYPE_NEXT_MONTH)) {
                    $billRet = $billModel->updateRepaymentAmount($customerId, $amount, Constant::PAY_TYPE_NEXT_MONTH);
                    if ($billRet) {
                        D("MerchantUser")->updateBalance($merchantId, $merchantGainAmount);
                        // $amount 已经减过首单优惠和商户满减优惠了
                        D("Customer")->updateBalance($customerId, -$amount);
                    }
                } else {
                    $customerBill = [
                        'customer_id' => $customerId,
                        'type' => Constant::PAY_TYPE_NEXT_MONTH,
                        'repayment_amount' => $amount,
                        'bill_date' => $billModel->billDate(),
                        'add_time' => time()
                    ];
                    $billId = $billModel->add($customerBill);
                    if ($billId) {
                        D("MerchantUser")->updateBalance($merchantId, $merchantGainAmount);
                        D("Customer")->updateBalance($customerId, -$amount);
                    }
                }
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                "amount" => $consumeAmount,
                "repay_type" => Constant::PAY_TYPE_NEXT_MONTH,
                "repay_date" => Constant::BILL_LAST_DAY,
                "repay_total" => $amount
            ];
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        //生成客户端需要的数据
        $this->generateClientData($data, $status, $ret);

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 生成客户端需要的数据
     * @param $customer
     * @param $status
     * @param $ret
     */
    private function generateClientData($customer, $status, &$ret)
    {
        $customerId = $customer['id'];
        $customer = D("Customer")->where(['id' => $customerId])->find();
        $data = [
            'credit' => $customer['amount'],
            'balance_amount' => $customer['balance_amount'],
            'max_amount' => Constant::MAX_CREDIT_AMOUNT,
            'is_need_verify' => 1 //0不需要审核，1需审核
        ];
        $retData = [];
        if (is_array($ret['data']) && is_array($ret['data'])) {
            $retData = $ret['data'];
        }
        //审核成功
        if (ConsumeHistoryModel::STATUS_REVIEWED == $status) {
            //SendSMS::reviewedPass($customer['mobile']);
            $data['is_need_verify'] = 0;
        }
        //等待审核
        if (ConsumeHistoryModel::STATUS_WAIT_REVIEWED == $status) {
            //SendSMS::waitReviewed($customer['mobile']);
            $data['is_need_verify'] = 1;
            $ret['code'] = Constant::SUCCESS;
        }
        $ret['data'] = array_merge($retData, $data);
    }

    //保存位置信息
    private function saveLocationHistory()
    {
        $locationModel = D("CustomerLocationHistory");
        $locationData = [
            'customer_id' => I('post.customer_id', 0, 'intval'),
            'province' => I("post.province", ''),
            'city' => I("post.city", ''),
            'country' => I("post.country", ''),
            'address' => I("post.address", ''),
            'location' => I("post.location", ''),
            'add_time' => time()
        ];
        Log::write("Customer location:" . json_encode($locationData), Log::INFO);
        $locationModel->add($locationData);
    }

    /**
     * 计算分期本金和利息,单位分
     * @param int $amount
     * @return array
     */
    private function getInstallmentDetail($amount)
    {
        return D("CustomerBill")->getInstallmentDetail($amount);
    }

    /*******************************************************************************************
     * 功能描述：用户密码重置
     * 创建日期：2016-08-02
     * 入参：
     *     "customer_id": "用户ID",
     *     "password": "经加密后的密文(需要客户端与服务端统一规则)",
     *     "verify_code": "验证码"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *******************************************************************************************/
    public function resetPassword()
    {
        try {
            //0.获取上行参数
            $mobile = I('post.mobile', 0, 'int');  //手机号
            $type= I('post.type', 0, 'int');  //设备号
            $password = I('post.password', '', 'string');  //密码
            $verifyCode = I('post.verify_code', 0, 'int'); //验证码
            if (!$mobile || !$password || !$verifyCode || !$type) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //1.根据客户手机号校验用户是否存在
            $customerId = M('Customer')->where(['mobile' => $mobile])->getField('id');
            if (!$customerId) {
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }
            if (count($customerId) > 1){
                BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
            }

            //2.验证码校验
            if(Constant::PAY_PASSWORD == $type){
                $verifyType = Constant::VERIFY_CODE_TYPE_MODIFY;
                $setElement = 'pay_pass';
            }
            if(Constant::LOGIN_PASSWORD == $type){
                $verifyType = Constant::VERIFY_CODE_TYPE_LOGIN;
                $setElement = 'password';
            }
            $sentVerifyCode = SendSMS::getVerifyCode($mobile, $verifyType);
            if (!$sentVerifyCode) {   //验证码超时
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }
            Log::sms_write('============================ ***验证码有效性校验|用户输入的$verifyCode:'.$verifyCode.'***==================================================');
            Log::sms_write('============================ ***验证码有效性校验|服务端发送的$sentVerifyCode:'.$sentVerifyCode.'***==================================================');

            if ($verifyCode != $sentVerifyCode) {  //验证码不正确
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            //3.密码重置
            $res = M('Customer')->where(['id' => $customerId])->setField($setElement, get_enc_password($password));
            Log::write("reset ".$setElement.":".M('Customer')->getLastSql(), Log::DEBUG);
            if ($res) {
                $ret = Constant::getReturn(Constant::SUCCESS);
            } else {
                BusinessException::throwException(Constant::FAILED);
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /***************************************************************************
     * 功能描述：用户授权提示语
     * 创建时间：2016-08-06
     * 入参：
     *     "customer_id": "用户ID",
     *     "permission_type":"0:通话记录；1:通讯录；2:地理位置；3:摄像头；。。。",
     *     "device_id":"设备id",
     *     "device_os":"设备的操作系统：android，ios，winphone",
     *     "device_os_version":"设备系统的版本",
     *     "device_mode":"设备类型：nokia3100",
     *     "device_brand":"品牌：nokia"
     * 出参：
     *      提示描述信息
     ***************************************************************************/
    public function getOpenPermissionHint()
    {
        try{
            //0.参数校验
            $data['permission_type'] = I('post.permission_type', 0, 'int');
            $data['device_id'] = I('post.device_id', '', 'string');
            $data['device_os'] = I('post.device_os', '', 'string');
            $data['device_os_version'] = I('post.device_os_version', '', 'string');
            $data['device_mode'] = I('post.device_mode', '', 'string');
            $data['device_brand'] = I('post.device_brand', '', 'string');
            $customerId = I('post.customer_id', 0, 'string');

            //1.获取机型对应权限的打开方式（如果没有则录入该机型数据）
            $deviceInfo = M('deviceInfo')->where(['device_brand' => $data['device_brand'], 'device_mode'=>$data['device_mode']])->find();
            if(!count($deviceInfo)){
                $data['add_time'] = date('Y-m-d H:i:s',time());
                $res = M('deviceInfo')->add($data);
            }else{
                $res = $deviceInfo['id'];
                $tips = json_decode($deviceInfo['permission_describe'], true);
                $tips['title'] = "亲！您的".Constant::$permissionMsg[$data['permission_type']].Constant::PERMISSION_TIPS;
            }

            //2.保存用户机型数据
            $customer = array(
                'device_info_id' => $res,
                'customer_id' => $customerId,
                'permission_type' => $data['permission_type'],
                'device_id' => $data['device_id'],
                'add_time' => date('Y-m-d H:i:s',time())
            );
            $res = M('customerDeviceHis')->add($customer);
            //该用户通过该机型申请超过>=3次，则默认放行
            $permission = D('Customer')->getCountPermission($customerId, $data['device_id'], $data['permission_type']);
            if($permission >= 3){
                $ret = Constant::getReturn(Constant::SUCCESS);
            }
            //不放行则则提示用户权限问题
            else if(!count($deviceInfo) || !$tips['options']){
                BusinessException::throwException(Constant::NO_PERMISSION_TIPS);
            }else{
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data'] = $tips;
            }
        }catch(BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    //用户登录old 1.2之前的老版本在调用
    public function signIn()
    {
        try {
            //返回信息
            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    
    public function getCustomerList()
    {
        try{
            $key = I('post.mobile_key', 1, 'int');
            $tool_id = I('post.tool_id', 0, 'int');
            $product_id = I('post.product_id', 0, 'int');
            $admin_id = I('post.admin_id', 0, 'int');
            if(!$admin_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //检验业务员是否存在
            $admin = M('AdminUsers')->where(['id'=>$admin_id, 'user_status'=>1])->find();
            if(!$admin){
                BusinessException::throwException(Constant::USER_NOT_FOUNT);
            }

            //根据业务员省份id获取对应的所有的county_id
            $county_id_str = 0;
            if($admin['provice_id']){
                $county_id_str = D('Position')->getAllCountyIdByProviceId($admin['provice_id']);
            }
            if($tool_id == CustomerModel::SEARCH_TYPE_ASSURE){
                $product_id .= ', 1';  //增加次月还款方式
            }

            $search['tool_id'] = $tool_id;
            $search['product_id'] = $product_id;
            $ret = Constant::getReturn(Constant::SUCCESS);
            if(strlen($key) > 1){
                $res = D('Customer')->getIsnotLocalCustomerList($key, $search, $county_id_str);
                $ret['data'] = $res;
            }else{
                $ret['data'] = [];
            }
        }catch(BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function UpdateCustomer()
    {
        try {
            $mobile = I('post.mobile', 0, 'int');
            $opr_id = I('post.opr_id', 0, 'int');
            if(!$mobile || !$opr_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if(!is_mobile($mobile)){
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }

            //业务员是否存在
            $user = M('AdminUsers')->where(['id'=>$opr_id, 'user_status'=>1])->find();
            if(!$user){
                BusinessException::throwException(Constant::USER_NOT_FOUNT);
            }

            $res = D('Customer')->has(['mobile'=>$mobile]);
            //更新用户的本地人权限
            if(!($upd = M('Customer')->where(['mobile'=>$mobile])->setField(['is_local'=>1]))){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            //记录日志
            $data = [
                'user' => $opr_id,
                'object' => $res['id'],
                'action' => 1,
                'last_time' => time()
            ];
            $res = M('AdminCommonActionLog')->add($data);
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 记录弹出通知 ******/
    public function RecordPopupTimes()
    {
        try{
            $customer_id = I('post.customer_id', 0, 'int');
            $type = I('post.type', 1, 'int');
            if(!$customer_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //检查用户是否存在
            D('Customer')->has($customer_id);
            $already_nums = 1;

            //记录用户通知次数
            $record = M('CustomerPopupLog')->where(['customer_id'=>$customer_id, 'type'=>$type])->find();
            if(!$record){
                $data = [
                    'type'=>$type,
                    'customer_id'=>$customer_id,
                    'already_nums'=>$already_nums,
                    'update_time'=>date('Y-m-d H:i:s', time()),
                ];
                if(false == M('CustomerPopupLog')->add($data)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            } else if (($record['already_nums'] < Constant::POPUP_TIMES_DEFLAUT)){
                $already_nums = isset($record['already_nums']) ? $record['already_nums']+1 : 1;
                $data = ['type'=>$type, 'customer_id'=>$customer_id, 'already_nums'=>$already_nums, 'update_time'=>date('Y-m-d H:i:s', time())];
                if(false == M('CustomerPopupLog')->where(['customer_id'=>$customer_id, 'type'=>$type])->save($data)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }

            $res = ['already_nums'=>$already_nums, 'hope_nums'=>Constant::POPUP_TIMES_DEFLAUT];
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res;
        } catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /**
     * 获取用户app列表
     */
    public function getUserAppList(){
        try{
            $applists = I('post.appList', '', 'string');
            $customerId = I('post.customer_id', 0, 'string');
            if(!$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //app字符串处理
            $applist = substr($applists,0,strlen($applists)-1);
            //检查用户是否存在
            D('Customer')->has($customerId);
            $time = time();
            $data = [
                'applist'=>$applist,
                'customer_id'=>$customerId,
                'add_time'=>$time
            ];
            if(false == M('CustomerAppList')->add($data)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
}
